package com.zw.scancodelogin.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.zw.scancodelogin.pojo.WeChatUser;
import com.zw.scancodelogin.utils.WeChatUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

@Slf4j
@RestController
@CrossOrigin
public class WeChatController {

    private WeChatUser weChatUser;

    @GetMapping("wxCheck")
    public String wxSignatureCheck(
            @RequestParam(value = "signature") String signature,
            @RequestParam(value = "timestamp") String timestamp,
            @RequestParam(value = "nonce") String nonce,
            @RequestParam(value = "echostr") String echostr
    ) {
        log.info("收到微信校验请求，echostr：{}", echostr);
        return echostr;
    }

    @GetMapping("/wxLogin")
    public void wxLoginPage(HttpServletResponse response) throws IOException {
        // redirectUrl是回调的地址，注意要转成 URLEncode 格式
        String redirectUrl = URLEncoder.encode("https://66edbac2.r6.cpolar.cn/wxCallback", "UTF-8");
        /*
         * https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
         * */
        // 构建二维码链接地址
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxcf51ed4bfafcecdb&redirect_uri="
                + redirectUrl + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

        // 输出二维码，扫描后跳转到上面的地址
        response.setContentType("image/png");

        QrCodeUtil.generate(url, 300, 300, "jpg", response.getOutputStream());
    }

    @GetMapping("/wxCallback")
    public String wxCallback(String code, String state, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        // 设置 响应编码 为 UTF-8
        response.setContentType("text/html;charset=UTF-8");

        log.info("收到微信回调，code：{}", code);
        this.weChatUser = WeChatUtil.getUserInfo(code);
        return "<h1>扫码成功</h1>";
    }

    @GetMapping("/getUser")
    public WeChatUser getUser(HttpSession session) {
        return this.weChatUser;
    }

    @DeleteMapping("/delUser")
    public String delUser(HttpSession session) {
        this.weChatUser = null;
        log.info("删除用户信息");
        return "删除成功";
    }

}
